package service;

import java.util.Date;

import dao.UserDao;

import framework.Trait;
import framework.server.ServerException;
import framework.service.MessageService;

import message.CheckUserMsg;
import message.RegisterUserMsg;
import message.UserMsg;
import model.UserBean;
import model.UserMode;

public class UserService extends MessageService {

	private UserDao dao;

	public UserService(Trait container, String serviceName) {
		super(container, serviceName);
	}

	@Override
	public void init() throws ServerException {
		dao = new UserDao();
	}

	public void process(CheckUserMsg request) {
		String agent = request.getAgentName();
		String username = request.getUserName();
		String password = request.getPassword();
		int result = checkUser(username, password);
		UserMsg answerMsg = new UserMsg(result);
		sendMessage(answerMsg, getName(), agent);
	}

	public void process(RegisterUserMsg request) {
		String agent = request.getAgentName();
		String username = request.getUserName();
		String password = request.getPassword();
		String email = request.getEmail();
		Date birth = request.getBirth();
		int result = registerUser(username, password, email, birth);
		UserMsg answerMsg = new UserMsg(result);
		sendMessage(answerMsg, getName(), agent);
	}

	private int checkUser(String username, String password) {
		UserBean user = dao.getUserByName(username);
		if ((user == null) || !user.checkPass(password)) {
			return -2;
		}
		return 0;
	}

	private int registerUser(String username, String password, String email, Date birth) {
		if (dao.getUserByName(username) != null) {
			return -1;
		}
		if (dao.getUserByEmail(email) != null) {
			return -2;
		}
		UserBean user = new UserBean(username, password, email, UserMode.User, birth);
		dao.insert(user);
		return 0;
	}
}
